package com.dayu.gulimall.ware.service.impl;

import com.dayu.common.exception.NoStockException;
import com.dayu.common.utils.R;
import com.dayu.gulimall.ware.feign.ProductFeignClient;
import com.dayu.gulimall.ware.vo.OrderItemVo;
import com.dayu.gulimall.ware.vo.SkuHasStockVo;
import com.dayu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayu.common.utils.PageUtils;
import com.dayu.common.utils.Query;

import com.dayu.gulimall.ware.dao.WareSkuDao;
import com.dayu.gulimall.ware.entity.WareSkuEntity;
import com.dayu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private WareSkuDao wareSkuDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long wareId, Long skuId, Integer skuNum) {

        List<WareSkuEntity> list = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (!CollectionUtils.isEmpty(list)) {
            this.baseMapper.updateStock(wareId, skuId, skuNum);
        } else {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            try {
                R info = productFeignClient.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (skuInfo != null) {
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                } else {
                    wareSkuEntity.setSkuName("");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.baseMapper.insert(wareSkuEntity);
        }
    }

    @Override
    public List<SkuHasStockVo> hasStock(List<Long> skuIds) {
        List<SkuHasStockVo> vos = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            Long count = this.baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            //TODO 默认查不到的都算有库存
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    /**
     * 为订单锁定库存
     * 默认只要是运行时异常都会回滚
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean lockOrderStock(WareSkuLockVo vo) {

        List<OrderItemVo> locks = vo.getLocks();

        //查询每个商品的所有有库存的仓库
        List<SkuWarehasStock> collect = locks.stream().map(item -> {
            SkuWarehasStock stock = new SkuWarehasStock();
            stock.setSkuId(item.getSkuId());
            stock.setNum(item.getCount());
            //查询有库存id
            List<Long> ids = wareSkuDao.listWarehasStock(item.getSkuId());
            stock.setWareId(ids);
            return stock;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWarehasStock stock : collect) {
            boolean skuLocked = false;

            List<Long> wareIds = stock.getWareId();
            Long skuId = stock.getSkuId();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            //锁库存
            for (Long wareId : wareIds) {
                long count = wareSkuDao.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    //锁定成功
                    skuLocked = true;
                    break;
                } else {

                }
            }

            //如果没有锁定成功，还是要抛异常
            if (!skuLocked) {
                throw new NoStockException(skuId);
            }
        }



        return null;
    }

    @Data
    class SkuWarehasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }


}